#include "CheckersPiece.h"
#include "CheckersApp.h"
#include "CheckersBoard.h"

const float CheckersPiece::CHECKERS_PIECE_RADIUS = 0.4f;

CheckersPiece::CheckersPiece(CheckersApp *app):
	app(app)
{
}

CheckersPiece::~CheckersPiece()
{
}

void CheckersPiece::Draw()
{
	// Configure input assembler
	ID3D11Buffer *vertexBuffers[] = {app->VBCylinder()};
	UINT stride = sizeof(CheckersApp::Vertex), offset = 0;
	app->D3DDeviceContext()->IASetIndexBuffer(app->IBCylinder(), DXGI_FORMAT_R16_UINT, 0);
	app->D3DDeviceContext()->IASetInputLayout(app->InputLayout());
	app->D3DDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	app->D3DDeviceContext()->IASetVertexBuffers(0, 1, vertexBuffers, &stride, &offset);

	// Configure shaders
	ID3D11Buffer *cbPerObject = app->CBPerObject();
	app->D3DDeviceContext()->PSSetShader(app->PSColor(), NULL, 0);
	app->D3DDeviceContext()->PSSetConstantBuffers(0, 1, &cbPerObject);
	app->D3DDeviceContext()->VSSetShader(app->VSColor(), NULL, 0);
	app->D3DDeviceContext()->VSSetConstantBuffers(0, 1, &cbPerObject);

	// Update shader parameters
	CheckersApp::ObjectParams objParams;
	objParams.g_worldViewProj = DirectX::XMMatrixMultiplyTranspose(worldMatrix, app->ViewProjMatrix());
	objParams.g_color = color;
	app->D3DDeviceContext()->UpdateSubresource(cbPerObject, 0, NULL, &objParams, 0, 0);

	// Draw the checkers piece
	app->D3DDeviceContext()->DrawIndexed(NUM_INDICES, 0, 0);
}

void CheckersPiece::PlaceOnBoard(const CheckersBoard *board, int i, int j)
{
	// First translate onto correct position in board local space, then apply board world transform
	worldMatrix = DirectX::XMMatrixMultiply(
		DirectX::XMMatrixTranslation(-3.5f + 1.0f*j, 0.1f, -3.5f + 1.0f*i),
		board->WorldMatrix());
}

void CheckersPiece::Translate(const DirectX::XMVECTOR &delta)
{
	worldMatrix = DirectX::XMMatrixMultiply(
		worldMatrix,
		DirectX::XMMatrixTranslationFromVector(delta));
}